import React , {Component} from 'react'

import {Dimmer,Segment,Form,Button,Loader,Progress} from "semantic-ui-react";
import WalletTools from "../servises/service"
import PubSub from "pubsub-js";

class KeyStoreTab extends Component {
    state = {
        loading:false,
        progress:'',
        pwd:'',
        keyStore:'',
        wallet:{},
    }

    handleChange = (e,{name,value})=>{
        this.setState({[name]:value})
    }


    handleKeyImport = async ()=>{
        let {keyStore,pwd} = this.state;
        try{
            this.setState({loading:true})
            let wallet = await WalletTools.newWalletFromJson(keyStore,pwd,(progress)=>{
                this.setState({progress})
            })

            this.setState({wallet})
            PubSub.publish("onLoginSuccessfully", wallet)
            this.setState({loading:false})
        }catch (e) {
            alert(e)
            this.setState({loading:false,progress:''})

        }
    }



    render (){

        return(
            <Dimmer.Dimmable as={Segment} dimmed={this.state.loading}>
                {this.state.progress && (
                    <Progress
                        style={{
                            width: "100%"
                        }}
                        percent={parseInt(this.state.progress * 100)}
                        inverted
                        success
                        progress
                    />
                )}
                <Dimmer active={this.state.loading} inverted>
                    <Loader active={this.state.loading} inline />
                </Dimmer>
                <Form size="large">
                    <Segment>
                        <Form.TextArea
                            placeholder="keystore为json格式"
                            name="keyStore"
                            value={this.state.keyStore}
                            onChange={this.handleChange}
                        />

                        <Form.Input
                            fluid
                            icon="lock"
                            iconPosition="left"
                            placeholder="Password"
                            type="password"
                            name="pwd"
                            value={this.state.pwd}
                            onChange={this.handleChange}
                        />
                        <Button
                            color="teal"
                            fluid
                            size="large"
                            onClick={this.handleKeyImport}
                        >
                            导入(下一步)
                        </Button>

                    </Segment>
                </Form>
            </Dimmer.Dimmable>
        )
    }


}

 export default KeyStoreTab